package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFile(JoinPoint joinPoint) {
        log.info("切面类被执行了~");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType type = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args == null && args.length == 0) {
            return;
        }
        Object arg = args[0];
        Class clazz = arg.getClass();

        if (type == OperationType.INSERT) {

            try {
                Method setCreateTime = clazz.getDeclaredMethod("setCreateTime", LocalDateTime.class);
                setCreateTime.invoke(arg,LocalDateTime.now());

                Method setUpdateTime = clazz.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(arg,LocalDateTime.now());

                Method setCreateUser = clazz.getDeclaredMethod("setCreateUser", Long.class);
                setCreateUser.invoke(arg, BaseContext.getCurrentId());

                Method setUpdateUser = clazz.getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else {
            try {
                Method setUpdateTime = clazz.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(arg,LocalDateTime.now());

                Method setUpdateUser = clazz.getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

}























